<?php

use Illuminate\Database\Capsule\Manager as DB;

class Order_AftersaleController extends CommonController
{
    public function indexAction()
    {
        $params = $this->get();
        json(['code' => 1, 'msg' => '售后列表', 'data' => orderaftersaleModel::getList($params)]);
    }


    /**
     * 详情
     */
    public function detailAction()
    {
        $params = $this->get();

        if (empty($params['id'])) {
            throw new Exception('售后id不能为空');
        }

        json(['code' => 1, 'msg' => '售后详情', 'data' => orderaftersaleModel::detail($params)]);
    }



    // 申请售后
    public function aftersaleAction()
    {
        $params = $this->getPost();

        try {
            Validate::check($params, [
                'type' => ['role' => 'required', 'msg' => '售后类型'],
                'order_id' => ['role' => 'required', 'msg' => '订单id'],
                'order_item_id' => ['role' => 'required', 'msg' => '订单商品'],
                'phone' => ['role' => 'required', 'msg' => '联系方式'],
                'reason' => ['role' => 'required', 'msg' => '售后原因'],
            ]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

        json(['code' => 1, 'msg' => '申请成功', 'data' => orderaftersaleModel::aftersale($params)]);
    }


    // 取消售后单
    public function cancelAction()
    {
        $params = $this->getPost();

        try {
            Validate::check($params, ['id' => ['role' => 'required', 'msg' => '售后id']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

        json(['code' => 1, 'msg' => '取消成功', 'data' => orderaftersaleModel::operCancel($params)]);
    }

    // 删除售后单
    public function deleteAction()
    {
        $params = $this->getPost();

        try {
            Validate::check($params, ['id' => ['role' => 'required', 'msg' => '售后id']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

        json(['code' => 1, 'msg' => '删除成功', 'data' => orderaftersaleModel::operDelete($params)]);
    }

    // 退货寄回快递信息
    public function expressAction()
    {
        $order_aftersale_id = $this->getPost('order_aftersale_id', 0);
        $express_code = $this->getPost('express_code', '');
        $express_no = $this->getPost('express_no', '');
        if (empty($order_aftersale_id)) {
            throw new Exception('售后信息不存在');
        }
        if (empty($express_code)) {
            throw new Exception('请选择快递公司');
        }
        if (empty($express_no)) {
            throw new Exception('请填写快递单号');
        }

        $express_name = DB::table('express')->where('code', $express_code)->value('name') ?: '';
        DB::table('order_aftersale_return')
            ->where('order_aftersale_id', $order_aftersale_id)
            ->update(['express_code' => $express_code, 'express_name' => $express_name, 'express_no' => $express_no]);

        json(['code' => 1, 'msg' => '', 'data' => true]);
    }
}
